package com.shujia

import scala.io.Source

object Demo19WordCount {

  def main(args: Array[String]): Unit = {

    /**
      * 统计单词的数量
      *
      */

    val lines: List[String] = Source.fromFile("scala/data/words.txt").getLines().toList


    val words: List[String] = lines.flatMap(line => line.split(","))


    //以单词分组
    val map: List[(String, List[String])] = words.groupBy(word => word).toList

    //统计每个单词的数量
    val count: List[String] = map.map(kv => {
      //获取map的key
      val word: String = kv._1

      //获取map的value
      val value: List[String] = kv._2

      //统计每个单词的数量
      val length: Int = value.length

      s"$word\t$length"
    })



    count.foreach(println)

    println("=" * 100)

    Source
      .fromFile("scala/data/words.txt")
      .getLines()
      .toList
      .flatMap(_.split(","))
      .groupBy(word => word)
      .toList
      .map(kv => s"${kv._1}\t${kv._2.length}")
      .foreach(println)


  }

}
